package com.hzit.servlet;

import cn.hutool.core.util.StrUtil;
import com.hzit.entity.User;
import com.sun.corba.se.impl.dynamicany.DynStructImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 类名：
 * 作者：WF
 * 功能：用户Servlet
 */
@WebServlet("/user")
public class UserServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1. 得到请求参数
		String cmd = req.getParameter("cmd");
		//2. 根据参数调用不同的方法
		if(StrUtil.isNotBlank(cmd)){
			if("login".equals(cmd)){
				login(req,resp);
			}
		}
	}

	//2. 用户登录处理
	private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//2.1 得到用户名及密码
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		//2.2 判断用户名及密码
		if("admin".equals(username) && "123".equals(password)){     // 登录成功后将用户信息放到session中
			//2.2.1 得到session
			HttpSession session = req.getSession();
			//2.2.2 构造用户并放到session
			User user = new User(username,password);
			session.setAttribute("user",user);
			//2.2.3 跳转到欢迎页面
			resp.sendRedirect("/index.jsp");
		}else{          // 如果用户名或密码输入不对，就重新登录
			resp.sendRedirect("/login.jsp");
		}
	}
}
